package com.viethp.mt.common;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.viethp.mt.activities.R;
import com.viethp.mt.objects.Position;
import com.viethp.mt.objects.User;

public class CommonHelper {
	// Show Toast
	public static void showToast(Context context, String str_message) {
		Toast toast = Toast.makeText(context, str_message, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0);
		toast.setDuration(GlobalVariables.TOAST_TIME);
		toast.show();
	}

	public static void showToastInt(Context context, int str_message) {
		Toast toast = Toast.makeText(context, str_message, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0);
		toast.setDuration(GlobalVariables.TOAST_TIME);
		toast.show();
	}

	// Show Toast with 7s length
	public static void showToast7s(Context context, String str_message) {
		Toast toast = Toast.makeText(context, str_message, 7);
		toast.setGravity(Gravity.CENTER | Gravity.BOTTOM, 0, 0);
		toast.setDuration(7);
		toast.show();
	}

	public static int dptopx(float dp, Context context) {
		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		return (int) (metrics.density * dp + 0.5f);
	}

	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, Context context) {
		Bitmap bmResize = getResizedBitmap(bitmap,
				dptopx((float) 120, context), dptopx((float) 120, context));
		Bitmap output = Bitmap.createBitmap(bmResize.getWidth(),
				bmResize.getWidth(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bmResize.getWidth(),
				bmResize.getWidth());
		final RectF rectF = new RectF(rect);
		final float roundPx = 9;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);

		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	public static Bitmap getRoundedCornerBitmapGallery(Bitmap bitmap) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getWidth(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getWidth());
		final RectF rectF = new RectF(rect);
		final float roundPx = 9;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);

		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

		int width = bm.getWidth();

		int height = bm.getHeight();

		float scaleWidth = ((float) newWidth) / width;

		float scaleHeight = ((float) newHeight) / height;

		// create a matrix for the manipulation

		Matrix matrix = new Matrix();

		// resize the bit map

		matrix.postScale(scaleWidth, scaleHeight);

		// recreate the new Bitmap

		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
				matrix, false);

		return resizedBitmap;

	}

	public static String toMD5(String s) {
		try {
			// Create MD5 Hash
			MessageDigest digest = java.security.MessageDigest
					.getInstance("MD5");
			digest.update(s.getBytes());
			byte messageDigest[] = digest.digest();

			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++) {
				String hex = Integer.toHexString(0xFF & messageDigest[i]);
				if (hex.length() == 1)
					hexString.append('0');
				hexString.append(hex);
			}
			return hexString.toString().toUpperCase();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static boolean eMailValidation(String emailstring) {
		Pattern emailPattern = Pattern
				.compile("^[A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$");
		Matcher emailMatcher = emailPattern.matcher(emailstring);
		return emailMatcher.matches();
	}

	public static void loadwebsite(Activity at, String url) {
		Intent browserIntent = new Intent("android.intent.action.VIEW",
				Uri.parse(url));
		at.startActivity(browserIntent);
	}

	public static void showWarning(Context context, String str_message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("Warning").setMessage(str_message)
				.setIcon(R.drawable.ic_dialog_alert).setCancelable(false)
				.setPositiveButton("OK", null);
		builder.create().show();
	}

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static Bitmap getBitmapFromAsset(String filename, Context context) {
		Bitmap bm = null;
		try {
			InputStream is = context.getResources().getAssets().open(filename);
			bm = BitmapFactory.decodeStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bm;

	}

	public static void callGallery(Activity activity, int requestCode) {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		activity.startActivityForResult(
				Intent.createChooser(intent, "Select Picture"), requestCode);
	}

	public static Bitmap getImageBitmap(String url) {
		Bitmap bm = null;
		try {
			URL aURL = new URL(url);
			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
		} catch (IOException e) {
			Log.e("TAG", "Error getting bitmap", e);
		}
		return bm;
	}

	public static long toSecond(int mon, int day, int hour) {
		return mon * 2592000 + day * 86400 + hour * 3600;
	}

	public static long getCurrentDate() {
		Calendar currentDate = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat(
				"yyyy/MMM/dd HH:mm:ss");
		String dateNow = formatter.format(currentDate.getTime());
		long epoch = 0;
		try {
			epoch = formatter.parse(dateNow).getTime() / 1000;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return epoch;
	}

	public static long checkTimeLeft(long createDate, long currentDate, long exp) {
		long count = currentDate - createDate;
		if (exp > count)
			return exp - count;
		return -1;
	}

	public static String timeLeft(long timeleft) {
		int mon, date, hour, min, sec;
		min = (int) (timeleft / 60);
		sec = (int) (timeleft % 60);
		if (min == 0) {
			if (sec < 2)
				return sec + " sec";
			else
				return sec + " secs";
		} else if (min > 0 && min < 60 && sec != 0) {
			if (min < 2 && sec < 2)
				return min + " min " + sec + " sec";
			else if (min < 2 && sec > 1)
				return min + " min " + sec + " secs";
			else if (min > 1 && sec < 2)
				return min + " mins " + sec + " sec";
			else
				return min + " mins " + sec + " secs";
		} else if (min > 0 && min < 60 && sec == 0) {
			if (min < 2)
				return min + " min";
			else
				return min + " mins";
		} else {
			hour = min / 60;
			min = min % 60;
			if (hour < 24 && min != 0) {
				if (hour < 2 && min < 2)
					return hour + " hr " + min + " min";
				else if (hour < 2 && min > 1)
					return hour + " hr " + min + " mins";
				else if (hour > 1 && min < 2)
					return hour + " hrs " + min + " min";
				else
					return hour + " hrs " + min + " mins";
			} else if (hour < 24 && min == 0)
				return hour + " hr";
			else {
				date = hour / 24;
				hour = hour % 24;
				if (date < 30 && hour != 0) {
					if (date < 2 && hour < 2)
						return date + " day " + hour + " hr";
					else if (date < 2 && hour > 1)
						return date + " day " + hour + " hrs";
					else if (date > 1 && hour < 2)
						return date + " days " + hour + " hr";
					else
						return date + " days " + hour + " hrs";
				} else if (date < 30 && hour == 0)
					return date + " day";
				else {
					mon = date / 30;
					date = date % 30;
					if (date != 0) {
						if (mon < 2 && date < 2)
							return mon + " mon " + date + " day";
						else if (mon < 2 && date > 1)
							return mon + " mon " + date + " days";
						else if (mon > 1 && date < 2)
							return mon + " mons " + date + " day";
						else
							return mon + " mons " + date + " days";
					} else
						return mon + " mon";
				}
			}
		}
	}

	public static void setUserLogin(User user, Context context) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				GlobalVariables.PREFERENCES, 0);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putInt("USER_ID", user.getId());
		editor.putString("USER_NAME", user.getUserName());
		editor.putString("USER_EMAIL", user.getEmail());
		editor.putString("USER_PHONE", user.getPhone());
		editor.putString("USER_PASSWORD", user.getPassWord());
		editor.commit();
	}

	// Get previous email
	public static User getUserLogin(Context context) {
		User user = new User();
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				GlobalVariables.PREFERENCES, mode);
		user.setId(sharedPreferences.getInt("USER_ID", -1));

		user.setUserName(sharedPreferences.getString("USER_NAME", ""));
		user.setEmail(sharedPreferences.getString("USER_EMAIL", ""));
		user.setPhone(sharedPreferences.getString("USER_PHONE", ""));
		user.setPassWord(sharedPreferences.getString("USER_PASSWORD", ""));
		return user;
	}

	// Set login method
	public static void setLoginMethod(int type, Context context) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				GlobalVariables.PREFERENCES, 0);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putInt("LOGIN_METHOD", type);
		editor.commit();
	}

	// Get login method
	public static int getLoginMethod(Context context) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				GlobalVariables.PREFERENCES, mode);
		return sharedPreferences.getInt("LOGIN_METHOD", GlobalVariables.LOGOUT);
	}

	// Set NEW_REG
	public static void setNewReg(boolean isAdd, Context context) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				GlobalVariables.PREFERENCES, 0);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putBoolean("NEW_REG", isAdd);
		editor.commit();
	}

	// Get NEW_REG
	public static boolean getNewReg(Context context) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				GlobalVariables.PREFERENCES, mode);
		return sharedPreferences.getBoolean("NEW_REG", false);
	}

	public static void setPosition(Position pos, Context context) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				GlobalVariables.PREFERENCES, 0);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString("LON", pos.getLon());
		editor.putString("LAT", pos.getLat());
		editor.commit();
	}

	public static Position getPosition(Context context) {
		Position pos = new Position();
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				GlobalVariables.PREFERENCES, mode);
		pos.setLon(sharedPreferences.getString("LON", ""));
		pos.setLat(sharedPreferences.getString("LAT", ""));
		return pos;
	}
}
